import processing.video.*;
import FaceDetect.*;

FaceDetect fd;
Capture cam;

// IIR smoothing.
final float alpha = .2;
float lastFaceX;
float lastFaceY;
float lastScale;

int MAX = 10;

int[] x = new int[MAX];
int[] y = new int[MAX];
int[] r = new int[MAX];
int[][] Faces = new int[MAX][3];

void setup(){
  size(640,480,P3D);
  cam = new Capture(this, width, height);
  fd = new FaceDetect(this);
  fd.start("haarcascade_frontalface_alt.xml", width, height, 5);
}

void draw(){
  if (cam.available()) {
    cam.read();
    Faces = fd.face(cam);
    int count = Faces.length;
    if (count>0) {
      float faceX = (alpha*Faces[0][0]) + ((1-alpha)*lastFaceX);
      float faceY = (alpha*Faces[0][1]) + ((1-alpha)*lastFaceY);
      float scale = (alpha*(height/float(Faces[0][2])/2.5)) + ((1-alpha)*lastScale);
      lastFaceX = faceX;
      lastFaceY = faceY;
      lastScale = scale;
      scale(scale);
      image(cam, (width/scale/2)-faceX,(height/scale/2)-faceY);
    } else {
      scale(lastScale);
      image(cam,(width/lastScale/2)-lastFaceX,(height/lastScale/2)-lastFaceY);
    }
  }
}

